package com.marmot.cloud.framework.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import jakarta.annotation.PostConstruct;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class SpringDocConfig {

    @Value("${server.port}")
    private String serverPort;

    @Value("${server.servlet.context-path:/}")
    private String serverContextPath;

    @Value("${springdoc.swagger-ui.path:/swagger-ui.html}")
    private String swaggerUiPath;

    @Value("${springdoc.api-docs.path:/v3/api-docs}")
    private String apiDocsPath;

    @PostConstruct
    public void init() {
        // Ensure context path ends with "/"
        if (!serverContextPath.endsWith("/")) {
            serverContextPath += "/";
        }

        // Ensure paths start with "/"
        if (swaggerUiPath != null && !swaggerUiPath.startsWith("/")) {
            swaggerUiPath = "/" + swaggerUiPath;
        }
        if (apiDocsPath != null && !apiDocsPath.startsWith("/")) {
            apiDocsPath = "/" + apiDocsPath;
        }

        // Print the URLs
        String swaggerUrl = "http://localhost:" + serverPort + serverContextPath + swaggerUiPath;
        String apiDocsUrl = "http://localhost:" + serverPort + serverContextPath + apiDocsPath;

        System.out.println("Swagger UI available at: " + swaggerUrl);
        System.out.println("API Docs available at: " + apiDocsUrl);
    }

    @Bean
    public OpenAPI openAPI() {
        return new OpenAPI()
                .info(new Info().title("API Documentation")
                        .description("API documentation for the application")
                        .version("v1.0.0")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("Open API Documentation")
                        .url("https://127.0.0.1/docs"));
    }

    @Bean
    public GroupedOpenApi groupedOpenApi() {
        return GroupedOpenApi.builder()
                .group("all")
                .pathsToMatch("/api/**")
                .build();
    }
}
